package admin

import (
	"gitee.com/jikey/elk-blog/app/model"
	"gitee.com/jikey/elk-blog/app/service"
	"gitee.com/jikey/elk-blog/pkg/e"
	"gitee.com/jikey/elk-blog/pkg/response"
	"github.com/flosch/pongo2"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"strconv"
)

type Category struct {
	Base
}

func (cat *Category) Index(c *gin.Context) {
	c.HTML(200, "admin/category/index.html", pongo2.Context{
		"title": "Welcome11222!",
		"greet": "hello",
		"obj":   "world",
	})
}

// List 列表
func (cat *Category) List(c *gin.Context) {
	data := make(map[string]interface{})

	data["rows"] = service.Category.GetBlogCategoryList("4")

	response.Success(c, data)
}

// Insert 新增保存
func (cat *Category) Insert(c *gin.Context) {
	category := &model.Category{}

	if err := c.ShouldBind(&category); err != nil {
		c.JSON(400, gin.H{
			"err": err.Error(),
		})
		return
	}

	err := service.Category.Create(category)

	if err != nil {
		logrus.Error("新增失败", err)
		response.Fail(c, e.ErrorInsert)
		return
	}

	response.Success(c, category)
}

// Update 修改
func (cat *Category) Update(c *gin.Context) {
	category := &model.Category{}

	if err := c.ShouldBind(&category); err != nil {
		c.JSON(400, gin.H{
			"err": err.Error(),
		})
		return
	}

	colId := strconv.Itoa(category.ColId)
	err := service.Category.Update(colId, category)

	if err != nil {
		logrus.Error("修改失败： ", err)
		response.Fail(c, e.ErrorUpdate)
		return
	}

	response.Success(c, category)
}

// Destory 删除
func (cat *Category) Destory(c *gin.Context) {
	id := c.PostForm("id")

	if row := service.Category.Delete(id); row > 0 {
		response.Success(c, id)
		return
	}

	response.Fail(c, e.ErrorDelete)
}
